package com.huluobo.a2301mdmdemo.pages

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.google.gson.Gson
import com.huluobo.a2301mdmdemo.R
import com.huluobo.a2301mdmdemo.demo.RedPackRainView
import com.huluobo.lib_base.BaseTitle
import com.hyphenate.EMCallBack
import com.hyphenate.EMMessageListener
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMMessage.ChatType
import com.hyphenate.chat.EMTextMessageBody
import com.hyphenate.util.DateUtils
import com.king.ultraswiperefresh.UltraSwipeRefresh
import com.king.ultraswiperefresh.rememberUltraSwipeRefreshState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.text.SimpleDateFormat

/**
 *  Created by LC on 2025/7/8.
 */

//声明聊天的bean,传递联系人和聊天类型(单聊,群聊,聊天室)
data class ChatBean(val contact: String, val chatType: ChatType, val name: String)

@Composable
fun ChatPage(navHostController: NavHostController, json: String) {
    val chatBean = Gson().fromJson(json, ChatBean::class.java)
    //消息的数据源
    val messageList = remember {
        SnapshotStateList<EMMessage>()
    }

    //发送的消息
    var messageString by remember {
        mutableStateOf("")
    }
    val emConversation = EMClient.getInstance().chatManager().getConversation(chatBean.contact)
    Log.e("TagA", "emConversation:$emConversation")
    if (emConversation != null) {
        messageList.clear()
        messageList.addAll(emConversation.allMessages)
    }
    //是否显示发送消息的进度条
    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //发送消息错误是否展示错误图标
    var isShowError by remember {
        mutableStateOf(false)
    }

    //是否显示时间
    var isShowTime by remember {
        mutableStateOf(true)
    }

    //消息列表的状态
    var listState = rememberLazyListState()

    //控制列表滚动到最下方的协程
    val coroutineScope = rememberCoroutineScope()

    var isShowLove by remember {
        mutableStateOf(false)
    }

    val state = rememberUltraSwipeRefreshState()

    //消息监听器
    val messageListener = EMMessageListener {
        //当接收到消息的时候,直接添加数据到数据中
//        Log.e("TagA", "接收到消息:$it")
        messageList.addAll(it)
        //滚动到最后一个item的位置
        coroutineScope.launch {
            listState.scrollToItem(messageList.size - 1)
        }
    }

    //类似于activity的生命周期
    DisposableEffect(Unit) {
        //带生命周期的协程作用域
        EMClient.getInstance().chatManager().addMessageListener(messageListener)

        //当页面销毁时
        onDispose {
            //销毁时移除掉消息监听器
            EMClient.getInstance().chatManager().removeMessageListener(messageListener)
        }
    }

    LaunchedEffect(key1 = state.isRefreshing, block = {
        val emConversation = EMClient.getInstance().chatManager().getConversation(chatBean.contact)
        if (messageList.size != 0) {
            val startId = messageList[0].msgId
            val messages = emConversation.loadMoreMsgFromDB(startId, 10)
            messageList.addAll(0, messages)
            state.isRefreshing = false
        }
    })

    Scaffold(
        bottomBar = {
            OutlinedTextField(
                value = messageString,
                onValueChange = { messageString = it },
                Modifier.fillMaxWidth(),
                trailingIcon = {
                    Icon(imageVector = Icons.Default.Send, contentDescription = "", modifier = Modifier.clickable {
                        if (messageString.isNotEmpty()) {
                            isShowProgress = true
                            //构建一条文本消息
                            val emMessage = EMMessage.createTextSendMessage(messageString, chatBean.contact)
                            //设置消息类型
                            emMessage.chatType = chatBean.chatType
                            messageList.add(emMessage)
                            //设置消息状态
                            emMessage.setMessageStatusCallback(object : EMCallBack {
                                override fun onSuccess() {
                                    isShowProgress = false
                                    //消息发送成功时,添加数据源
                                    messageString = ""
                                    isShowError = false
                                    //滚动到最后一个item的位置
                                    coroutineScope.launch {
                                        listState.scrollToItem(messageList.size - 1)
                                    }
                                }

                                override fun onError(code: Int, error: String?) {
                                    isShowProgress = false
                                    isShowError = true
                                    Log.e("TagA", "发送消息失败:$code,error:$error")
                                }
                            })
                            //发送消息
                            EMClient.getInstance().chatManager().sendMessage(emMessage)
                        }
                    })
                })
        }
    ) {
        Column(
            Modifier
                .padding(it)
                .padding(20.dp)
                .fillMaxWidth()
        ) {
            if (chatBean.chatType == ChatType.GroupChat) {
                BaseTitle(title = "与${chatBean.name}聊天", navHostController = navHostController)
            } else {
                BaseTitle(title = "与${chatBean.contact}聊天", navHostController = navHostController)
            }
            Spacer(modifier = Modifier.height(10.dp))
            UltraSwipeRefresh(state = state, onRefresh = { state.isRefreshing = true }, onLoadMore = {}) {
                LazyColumn(state = listState, content = {
                    itemsIndexed(messageList) { index, item ->
                        //判断当前消息列表是否是第一条数据,如果是第一条数据,肯定显示时间
                        if (index == 0) {
                            isShowTime = true
                        } else {
                            isShowTime =
                                !DateUtils.isCloseEnough(messageList[index].msgTime, messageList[index - 1].msgTime)
                        }
                        //判断2个消息之间的时间间隔是否大于30秒
                        ChatItem(
                            message = item,
                            isShowProgress,
                            index == messageList.lastIndex,
                            isShowError,
                            isShowTime
                        ) {
                            isShowError = false
                            //重新发送消息
                            isShowProgress = true
                            //构建一条文本消息
                            val emMessage = EMMessage.createTextSendMessage(messageString, chatBean.contact)
                            //设置消息类型
                            emMessage.chatType = chatBean.chatType
                            messageList.add(emMessage)
                            //设置消息状态
                            emMessage.setMessageStatusCallback(object : EMCallBack {
                                override fun onSuccess() {
                                    isShowProgress = false
                                    isShowError = false
                                    //消息发送成功时,添加数据源
                                    messageString = ""
                                    //滚动到最后一个item的位置
                                    coroutineScope.launch {
                                        listState.scrollToItem(messageList.size - 1)
                                    }
                                    if (messageString == "爱你") {

                                    }
                                }

                                override fun onError(code: Int, error: String?) {
                                    isShowProgress = false
                                    isShowError = true
                                    Log.e("TagA", "发送消息失败:$code,error:$error")
                                }
                            })
                            //发送消息
                            EMClient.getInstance().chatManager().sendMessage(emMessage)
                        }
                    }
//                items(messageList) {
//
//                }
                }, verticalArrangement = Arrangement.spacedBy(10.dp))
            }

            if (messageString == "爱你") {
                LoveView()
            }
        }
    }
}

@Composable
fun LoveView() {
    AndroidView(modifier = Modifier.fillMaxSize(), factory = {
        val redPackRainView = RedPackRainView(it)
        redPackRainView.start()
        redPackRainView
    })
}

@Composable
fun ChatItem(
    message: EMMessage,
    isShowProgress: Boolean,
    isLast: Boolean,
    isError: Boolean,
    isShowTime: Boolean,
    retry: () -> Unit
) {
    Log.e("TagA", "isLast:${isLast}")
    if (message.direct() == EMMessage.Direct.SEND) {
        Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
            if (isShowTime) {
                val time = SimpleDateFormat("HH:mm:ss").format(message.msgTime)
                Text(text = "$time", color = Color.LightGray, fontSize = 13.sp)
            }
            Row(
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(10.dp)
                    .fillMaxWidth()
            ) {
                if (isLast) {
                    if (isShowProgress) {
                        CircularProgressIndicator(Modifier.size(20.dp))
                    }
                    if (isError) {
                        Image(
                            painter = painterResource(id = R.drawable.baseline_error_24),
                            contentDescription = "",
                            Modifier.clickable {
                                //重新发送消息
                                retry()
                            })
                    }
                }
                Spacer(modifier = Modifier.width(10.dp))
                Text(text = (message.body as EMTextMessageBody).message)
                Spacer(modifier = Modifier.width(10.dp))
                AsyncImage(
                    model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                    contentDescription = "",
                    modifier = Modifier
                        .size(40.dp)
                        .clip(RoundedCornerShape(5.dp)),
                    contentScale = ContentScale.Crop
                )
            }
        }
    } else {
        Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
            val time = SimpleDateFormat("HH:mm:ss").format(message.msgTime)
            if (isShowTime) {
                val time = SimpleDateFormat("HH:mm:ss").format(message.msgTime)
                Text(text = "$time", color = Color.LightGray, fontSize = 13.sp)
            }
            Row(
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(10.dp)
                    .fillMaxWidth()
            ) {
                AsyncImage(
                    model = "https://img0.baidu.com/it/u=788800651,2030194952&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1730307600&t=9c17b588a934b0ccf76349e5e5b7ca08",
                    contentDescription = "",
                    modifier = Modifier
                        .size(40.dp)
                        .clip(RoundedCornerShape(5.dp)),
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.width(10.dp))
                Text(text = (message.body as EMTextMessageBody).message)
            }
        }
    }

}